package com.example.login.data

import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import androidx.room.RoomSQLiteQuery
import androidx.room.util.DBUtil
import com.example.login.data.model.LoggedInUser
import com.example.room.DbManager.getDB

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
class LoginDataSource {


    @SuppressLint("Range", "RestrictedApi")
    fun login(username: String, password: String,content:Context): Result<LoggedInUser> {
        var cursor: Cursor? = null
        try {
            val zRoomDB = getDB(content)
            val sql = "SELECT * FROM USER"
            val statement = RoomSQLiteQuery.acquire(sql, 0)
            zRoomDB.assertNotSuspendingTransaction()
            cursor = DBUtil.query(zRoomDB, statement, false, null)
            while (cursor.moveToNext()) {
                val account = cursor.getString(cursor.getColumnIndex("account"))
                if (username == account) {
                    val id = cursor.getString(cursor.getColumnIndex("id"))
                    val pas = cursor.getString(cursor.getColumnIndex("password"))
                    return if (password == pas) {
                        val fakeUser = LoggedInUser(id, username)
                        Result.Success(fakeUser)
                    } else {
                        Result.Error("密码错误")
                    }
                }
            }
        } catch (e: Throwable) {
            return Result.Error("登录错误 $e")
        } finally {
            cursor?.close()
        }
        return Result.Error("没找到")
    }

    //注册


    fun logout() {

    }
}